program define estimate_IRF_LP_state_dep, eclass
	
	syntax varlist(min = 2 max = 2), [L(int 8) K(int 4) ///
		min_lags_NW(int 4) Alpha(real 0.05)] 
	args dep_var dummy_var
	
	* Create matrices for storing results
	tempvar res
	matrix `res' = J(`l', 8, .)
	matrix colnames `res'  = lag IRF se lb ub df_resid K t_stat
	
	* Create temporary variables containing lags and leads
	quietly {
		forvalues ll = 1/`k' {
			tempvar `dep_var'_LAG`ll'
			tempvar `dummy_var'_LAG`ll'
			gen ``dep_var'_LAG`ll'' = l`ll'.`dep_var'
			gen ``dummy_var'_LAG`ll'' = l`ll'.`dummy_var'
		} 
		forvalues ll = 0/`l' {
			tempvar `dep_var'_LEAD`ll'
			gen ``dep_var'_LEAD`ll'' = f`ll'.`dep_var'
		}	
	}
	
	* Construct controls of the regression
	local controls
	quietly {
		forvalues ll = 1/`k' {
			tempvar `dep_var'_LAG`ll'_STATE0
			tempvar `dep_var'_LAG`ll'_STATE1
			gen ``dep_var'_LAG`ll'_STATE0' = ``dep_var'_LAG`ll'' * (1 - ``dummy_var'_LAG1')
			gen ``dep_var'_LAG`ll'_STATE1' = ``dep_var'_LAG`ll'' * ``dummy_var'_LAG1'
			local controls `controls' ``dep_var'_LAG`ll'_STATE0' /// 
				``dep_var'_LAG`ll'_STATE1'
		}
	}
	
	local controls `controls' ``dummy_var'_LAG1'
	
	* Construct controls for testing state dependence
	local controls_test
	forvalues ll = 1/`k' {
		local controls_test `controls_test' ``dep_var'_LAG`ll'' /// 
			``dep_var'_LAG`ll'_STATE1'
	}
	local controls_test `controls_test' ``dummy_var'_LAG1'
	
	* Calculate local projections
	forvalues ii = 1/`l' {
		local ii_1 = `ii' - 1
		local lags_NW = max(`min_lags_NW', `ii_1')
		
		* Main regression
		quietly newey ``dep_var'_LEAD`ii_1'' `controls', lag(`lags_NW')
		
		* Collect the results and calculate 
		* confidence intervals at the given significance level
		local se = _se[``dep_var'_LAG1_STATE1']
		local df_r = e(df_r)
		local t_crit = invt(`df_r', `alpha' / 2)
		
		matrix `res' [`ii', 1] = `ii'
		matrix `res' [`ii', 2] = _b[``dep_var'_LAG1_STATE1']
		matrix `res' [`ii', 3] = `se'
		matrix `res' [`ii', 4] = _b[``dep_var'_LAG1_STATE1'] + ///
			`t_crit' * `se'
		matrix `res' [`ii', 5] = _b[``dep_var'_LAG1_STATE1'] - ///
			`t_crit' * `se'
		matrix `res' [`ii', 6] = `df_r'
		matrix `res' [`ii', 7] = `k'
		
		* Test for state dependence
		quietly newey ``dep_var'_LEAD`ii_1'' `controls_test', lag(`lags_NW')
		local t_stat = _b[``dep_var'_LAG1_STATE1'] / _se[``dep_var'_LAG1_STATE1']
		matrix `res' [`ii', 8] = `t_stat'
	}
	
	ereturn matrix s `res'
	
end 
